<template>
  <div class="setting-container" style="margin-bottom: 30px;padding:30px 0">
    <el-card class="box-card" style="padding: 20px;">

      <el-button style="margin-bottom:20px;" @click="addModel">添加工作模式</el-button>

      <div class="setting-content" element-loading-text="加载中">
        <el-table
          v-loading="loading"
          stripe
          :header-cell-style="{ background: '#EEF1F4', color: '#646a73' }"
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column
            prop="id"
            label="工作模式编号"
            width="263"
          />
          <el-table-column
            prop="name"
            label="工作模式"
            width="263"
          />
          <el-table-column
            prop="workPatternTypeDesc"
            label="类型"
            width="200"
          />
          <el-table-column
            prop="workDate"
            label="工作日期"
            width="280"
          />
          <el-table-column
            prop="workStartMinute1"
            label="工作时间"
            width="200"
          >
            <template v-slot="{row}">
              <!-- {{ row.workStartMinute1 }} -->
              {{ convertMinutesToHours(row.workEndMinute1-row.workStartMinute1) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="controls"
            label="操作"
            min-width="120"
            fixed="right"
          >
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="editorBtn(row.id)">编辑</el-button>
              <span style="padding:0 5px">|</span>
              <el-button type="text" size="small" style="color:red" @click="remove(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页内容 -->
      <div class="block">
        <el-pagination
          :current-page.sync="pageParams.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 弹窗内容 -->
      <el-dialog
        title="新增工作模式"
        :visible.sync="dialogVisible"
        width="35%"
        @close="close"
      >
        <el-tabs v-model="activeName" style="padding:30px" @tab-click="handleClick">
          <el-tab-pane v-if="firstHidden" label="礼拜制" name="first">

            <el-form ref="ruleForm" label-position="left" label-width="80px" :model="firstWeeked" style="padding-top:20px" :rules="rules">

              <el-form-item label="名称" prop="name">
                <el-input v-model="firstWeeked.name" style="width: 350px;" />
              </el-form-item>

              <el-form-item label="活动区域" prop="monday">
                <el-checkbox v-model="firstWeeked.monday" :true-label="one" :false-label="two">周一</el-checkbox>
                <el-checkbox v-model="firstWeeked.tuesday" :true-label="one" :false-label="two">周二</el-checkbox>
                <el-checkbox v-model="firstWeeked.wednesday" :true-label="one" :false-label="two">周三</el-checkbox>
                <el-checkbox v-model="firstWeeked.thursday" :true-label="one" :false-label="two">周四</el-checkbox>
                <el-checkbox v-model="firstWeeked.friday" :true-label="one" :false-label="two">周五</el-checkbox>
                <el-checkbox v-model="firstWeeked.saturday" :true-label="one" :false-label="two">周六</el-checkbox>
                <el-checkbox v-model="firstWeeked.sunday" :true-label="one" :false-label="two"> 周日</el-checkbox>
              </el-form-item>

              <el-form-item label="工作时间" prop="tuesday">
                <el-time-picker
                  v-model="workTime"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 第二个切换 -->
          <el-tab-pane v-if="secondHidden" label="连续制" name="second">
            <el-form label-position="left" label-width="120px" :model="firstWeeked" style="padding-top:20px" :rules="rules">
              <el-form-item label="工作模式名称：" prop="name">
                <el-input v-model="firstWeeked.name" style="width: 350px;" />
              </el-form-item>
              <el-form-item label="连续工作天数：" prop="workDayNum">
                <!-- <el-input v-model="formLabelAlign.type" /> -->
                <span>上</span>
                <el-input v-model="firstWeeked.workDayNum" style="width: 140px; ">
                  <template #suffix>
                    <span>天</span>
                  </template>
                </el-input>
                <span>休</span>
                <el-input v-model="firstWeeked.restDayNum" style="width: 140px;padding-left: 10px;">
                  <template #suffix>
                    <span>天</span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="工作时间" prop="tuesday">
                <el-time-picker
                  v-model="workTime"
                  :picker-options="pickerOptions"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  format="MM-dd"
                />

              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitBtm">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>

import { workPatternsAPI, getModelAPI, getModelDetialAPI } from '@/api/employee/classes'
//
function newFirstWeeked() {
  return {
    'friday': 2,
    'monday': 2,
    'name': '',
    'operator': 57,
    'restDayNum': null,
    'saturday': 2,
    'sunday': 2,
    'thursday': 2,
    'tuesday': 2,
    'userType': 1,
    'wednesday': 2,
    'workDayNum': null,
    'workEndMinute1': null,
    'workPatternType': 1,
    'workStartMinute1': null

  }
}
const cityOptions = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
export default {
  data() {
    return {
      pickerOptions: {
        format: 'HH:mm', // 设置时间格式为小时和分钟
        selectableRange: '18:00:00 - 23:59:59' // 可选的时间范围
      },
      one: 1,
      two: 2,
      // 隐藏
      firstHidden: true,
      secondHidden: true,
      // 表单内容
      formLabelAlign: {
        name: '',
        region: '',
        type: '',
        checked: []
      },
      workTime: null,
      // 第一个礼拜制
      firstWeeked: newFirstWeeked(),
      // 加载的效果
      loading: false,
      cities: cityOptions,
      // 弹窗内容
      dialogVisible: false,
      //
      pageParams: {
        page: null,
        // 每页多少条
        pageSize: null
      },
      // 总分页
      totalCount: null,
      activeName: 'first',

      // 工作模式
      additionalProperties1: [],
      tableData: [],

      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        monday: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        tuesday: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        workDayNum: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        restDayNum: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]

      }
    }
  },
  // 分钟转消失
  computed: {
    convertMinutesToHours() {
      return function(minutes) {
        const hours = Math.floor(minutes / 60)
        return `${hours}小时`
      }
    }
  },
  created() {
    this.workPatterns()
  },
  mounted() {

  },
  methods: {
    // 保存按钮
    submitBtm() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          // 获取当前时间戳（以毫秒为单位）
          const currentTimestamp = Date.now()

          // const date = new Date(this.workTime[0].getTime())
          // 获取今天0点的时间戳
          const todayStartTimestamp = this.workTime[0].getTime()
          // 计算距离0点的分钟数
          const minutes = Math.floor((todayStartTimestamp - currentTimestamp) / 60000)

          // 获取分钟数
          // const minutes = date.getMinutes()
          this.firstWeeked.workStartMinute1 = minutes
          //
          // const date2 = new Date(this.workTime[1].getTime())
          // 获取今天0点的时间戳
          const StartTimestamp = this.workTime[1].getTime()
          // 计算距离0点的分钟数
          const minutes2 = Math.floor((StartTimestamp - currentTimestamp) / 60000)
          // 获取分钟数
          // const minutes2 = date2.getMinutes()
          this.firstWeeked.workEndMinute1 = minutes2

          await getModelAPI(this.firstWeeked)
          // console.log(res)
          console.log(this.firstWeeked)
          this.$message.success('添加成功')
          // 刷新数据
          this.workPatterns()
          this.dialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 编辑按钮
    async editorBtn(id) {
      this.dialogVisible = true
      const res = await getModelDetialAPI(id)
      if (res.data.workPatternType === 1) {
        this.activeName = 'first'
        this.firstHidden = true
        this.secondHidden = false
      } else {
        this.activeName = 'second'
        this.secondHidden = true
        this.firstHidden = false
      }
      this.firstWeeked = res.data

      // // 将分钟数转换为毫秒
      const millisecondsUntilMidnight = this.firstWeeked.workEndMinute1 * 60 * 1000
      const Midnight = this.firstWeeked.workStartMinute1 * 60 * 1000

      // 开始时间
      const midnightDate = new Date(millisecondsUntilMidnight)
      const midnighate = new Date(Midnight)
      this.workTime = []
      this.workTime.push(midnightDate)
      this.workTime.push(midnighate)
      console.log(12, this.workTime)
    },
    // 删除按钮
    remove(id) {
      this.$confirm('删除确定', '确定删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 关闭弹窗
    close() {
      this.$refs.ruleForm.resetFields()
      this.firstWeeked = newFirstWeeked()
    },
    // 获取数据
    async workPatterns() {
      this.loading = true
      const res = await workPatternsAPI(this.pageParams)
      this.loading = false
      this.tableData = res.data.items
      // console.log(res.data)
      this.totalCount = +res.data.counts
      this.pageParams.page = res.data.page
      this.pageParams.pageSize = res.data.pageSize
    },
    handleClick() {

    },
    // 添加排版模式
    addModel() {
      this.dialogVisible = true
    },
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.workPatterns()
      console.log(`每页 ${val} 条`)
    },
    // 点击页面切换数据
    handleCurrentChange(val) {
      this.pageParams.page = val
      this.workPatterns()
      console.log(`当前页: ${val}`)
    }
  }

}

</script>

<style  lang="scss" scoped>
 // 分页
    .block{
      padding-top:20px;
      // margin-bottom: 20px;
      text-align: center;
    }
    // checked

    ::v-deep.el-checkbox{
    margin-right: 24px;
}
::v-deep.el-input__suffix{
    right: 15px;
}
</style>
